package cn.jinjimi.app.poster.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;

import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.framework.helper.annotation.EventTraceWhenTrue;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.event.LocalEvent.ReaderShareEvent;
import cn.jinjimi.app.controller.event.NoticeEvent.NoticeEvent;
import cn.jinjimi.app.controller.event.NoticeEvent.NoticeNewAritcleEvent;
import cn.jinjimi.app.controller.event.NoticeEvent.NoticeNewJinjuEvent;
import cn.jinjimi.domain.data.dto.NoticePosterJinjuDTO;
import cn.jinjimi.app.entity.StudyIdeaDTO;
import cn.jinjimi.app.managers.NoticeManager;
import cn.jinjimi.app.poster.fragment.PosterContainerFragment;
import cn.jinjimi.app.poster.fragment.PosterFragment;
import cn.jinjimi.app.store.entity.NoticeEntity;
import cn.jinjimi.app.main.adapter.FragmentPageAdapter;
import cn.jinjimi.app.main.extend.BaseActivity;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.fragment.IdeaFragment;
import cn.jinjimi.app.main.fragment.ReaderArticleListFragment;
import cn.jinjimi.app.main.widget.PagerSlidingTabStrip;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Roy
 * Date: 2017/4/13
 */

public class ReaderActivity extends BaseActivity implements View.OnClickListener {

    private ViewPager mViewPager;
    private PagerSlidingTabStrip slidingTabStrip;
    private ReaderArticleListFragment mRecommendFragment, mArticleListFragment;

    public static final int JinjuCategoryCode = 13;

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_reader);
        setSwipeEnabled(true);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initFragment();

        initData();
    }

    private void initView() {
        mViewPager = (ViewPager) findViewById(R.id.at_container);
        // Bind the tabs to the ViewPager
        slidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.at_tabs);
    }

    private void initListener() {
        findViewById(R.id.btn_left).setOnClickListener(this);

        slidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(@EventTraceParam(value = BundleKey.POSITION, isValueAutoPlusOne = true) int position) {
                onPageRedState(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initFragment() {
        List<BaseFragment> fmList = new ArrayList<>();
        fmList.add(mRecommendFragment = ReaderArticleListFragment.create(ReaderArticleListFragment.TYPE_RECOMMEND));
        fmList.add(PosterFragment.create(PosterContainerFragment.LoadType.LOAD_CACHE_NET, null, PosterContainerFragment.DataType.JINJU_POSTER, JinjuCategoryCode, null, null));
        fmList.add(mArticleListFragment = ReaderArticleListFragment.create(ReaderArticleListFragment.TYPE_ALL_ARTICLE));
        StudyIdeaDTO study = StudyIdeaDTO.getStudyIdeaConfig();
        boolean hasIdeaTab = study != null && !StringUtils.isEmpty(study.url);
        if (hasIdeaTab) {
            IdeaFragment idea = new IdeaFragment();
            Bundle bundle = new Bundle();
            bundle.putString(BundleKey.URL, study.url);
            idea.setArguments(bundle);
            fmList.add(idea);
        }
        List<String> title = new ArrayList<>();
        title.add("推荐");
        title.add("金句");
        title.add("好文");
        if (hasIdeaTab)
            title.add("理念");
        FragmentPageAdapter adapter = new FragmentPageAdapter(getSupportFragmentManager(), fmList, title);

        mViewPager.setAdapter(adapter);
        slidingTabStrip.setViewPager(mViewPager);
        mViewPager.setCurrentItem(0);
    }

    private void initData() {
        int index = 0;
        if (getIntent().hasExtra(BundleKey.POSITION)) {
            String position = getIntent().getStringExtra(BundleKey.POSITION);
            if (Integer.parseInt(position) <= 2)
                index = Integer.parseInt(position);
        }
        mViewPager.setCurrentItem(index);

        analyse(index, index == 0);

        NoticeManager.getNoticesByCode(NoticeEntity.TypeNewJinju, NoticeEntity.TypeNewArticle);
    }

    private void analyse(@EventTraceParam(value = BundleKey.POSITION, isValueAutoPlusOne = true) int index, @EventTraceWhenTrue boolean shouldAnalyse) {
    }

    private void onPageRedState(int position) {
        slidingTabStrip.setRedStatus(position, false);
        if (position == 1) {
            NoticeManager.clickNoticeByCode(NoticeEntity.TypeNewJinju);
        } else if (position == 2) {
            NoticeManager.clickNoticeByCode(NoticeEntity.TypeNewArticle);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_left:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReaderShareEvent(ReaderShareEvent event) {
        ReaderShareEvent.State state = event.getState();
        if (AccountManager.getInstance().isLogin() && state == ReaderShareEvent.State.SUCCESS) {
            if (mRecommendFragment != null)
                mRecommendFragment.onReceiveEvent(event);
            if (mArticleListFragment != null)
                mArticleListFragment.onReceiveEvent(event);
        }
    }

    /* 金句红点事件 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoticeNewJinjuEvent(NoticeNewJinjuEvent event) {
        if (slidingTabStrip == null)
            return;
        if (event.state == NoticeEvent.StateAdd) {
            for (NoticePosterJinjuDTO dto : event.noticePosterDTO) {
                if (dto.categoryCode == JinjuCategoryCode) {
                    slidingTabStrip.setRedStatus(1, true);
                    return;
                }
            }
            onPageRedState(mViewPager.getCurrentItem());
        }
    }

    /* 好文红点事件 */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoticeNewAritcleEvent(NoticeNewAritcleEvent event) {
        if (slidingTabStrip == null)
            return;

        if (event.state == NoticeEvent.StateAdd && event.count > 0) {
            slidingTabStrip.setRedStatus(2, true);
        }

        onPageRedState(mViewPager.getCurrentItem());
    }
}
